#!/usr/bin/env python2.4
"""
runner
"""

import gc
import os
import sys
import logging
import threading
import PyLucene

from twisted.web import resource
from twisted.web import server

from twisted.application import service
from twisted.application import internet

from nokcene.core import NokceneServer
from logger import initLog
from xmlrpc import XMLRPCServer

# Ensure Python standard Thread is never used within Nokcene.
threading.Thread = PyLucene.PythonThread

from twisted.internet import reactor
reactor.suggestThreadPoolSize(10)

application = service.Application("Nokcene")

import config

class NokceneController (object):

	def __init__(self):

		#config_file = os.environ['CONFIG_FILE']
		initLog(config.nokcene_log_level, config.nokcene_file_log_daemon)

		self.log = logging.getLogger()

		#if config.nokcene_log_level == 'DEBUG':
		#	self.log.info("gc.set_debug(gc.DEBUG_LEAK)")
		#	gc.set_debug(gc.DEBUG_LEAK)

		self._root = resource.Resource()
		self.initializeResources()

	def initializeResources(self):
		"""Initialize server resources

		We could define SOAP here for instance as well.
		"""

		# Create a core server instance.
		core = NokceneServer(config.nokcene_directory_index)

		__create = False
		if not os.path.exists("%s/segments" % config.nokcene_directory_index) :
			__create = True

		# Optimize the indexes at startup
		core.optimize(None, creation=__create)

		# Adapt to RPC and register this resource.
		self._root.putChild('RPC2', XMLRPCServer( \
			core, config.nokcene_max_thread_number) \
		)

		self.log.info(
			"XML-RPC server "
			"is listening on port %s..." % config.nokcene_port)

	def start(self):
		self.log.info(
			"Indexes are located here : %s" % config.nokcene_directory_index)
		res = internet.TCPServer(config.nokcene_port,
						 server.Site(self._root))
		res.setServiceParent(application)

NokceneController().start()

